﻿/*
=============================================================================
Author:魏宝辉通过CodeSmithe生成
CreatedTime:2012-11-4
Description:CQuery_ReportList.aspx.cs页面代码
=============================================================================	
*/

using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using FineUI;
using FTchina.Library;
using FTchina.Logic;
using FTchina.Models;
using PWMIS.Common;
using PWMIS.DataMap.Entity;
using PWMIS.DataProvider.Adapter;
using PWMIS.DataProvider.Data;
using System.Web.UI.WebControls;
public partial class CQuery_ShowReport_cs : BasePage
{
    string theId = string.Empty;//显示的报表的ID
    string PageID = string.Empty;//关联表单 唯一字段 存储在cookie的key值
    string LinkReportID = string.Empty;//关联表单ID
    int PageSize = 20;
    AdoHelper adohelper;//查询用助手
    DBMSType dbtype;//本次查询的数据库类型
    string SqlFrom = string.Empty;//select * From x where x.id=3中的 x 
    string Colums = string.Empty;//select * From x where x.id=3中的 *
    string ExcelColums = string.Empty;//select * From x where x.id=3中的 * 导出Excel 需要As 列名 直观
    string SqlWhere = "  1=1 ";//select * From x where x.id=3中的 x.id=3 
    string OrderColum = string.Empty;//分页排序用

    int RowsCount = 0;//查询条件行数
    int RowsAllCount = 0;//查询条件个数


    List<Cquery_ColumList> Modlist;//生成查询条件用，提取条件语句也用到

    bool Replacemode = true;//工作与替换模式



   
    protected void Page_Load(object sender, EventArgs e)
    {


        theId = RequestHelper.SafeRequest(Request["id"]);
        PageID = RequestHelper.SafeRequest(Request["PageID"]);
        //LogHelper.Debug("Page_Load" + RequestHelper.GetCookie(PageID));
        GetReportInfo(theId);


    }

    /// <summary>
    /// 获取报表自身的数据，创建表头
    /// </summary>
    /// <param name="ItemID"></param>
    private void GetReportInfo(string ItemID)
    {
        FTchina.Models.CQuery_ReportList mCQuery_ReportList = FTchina.BLL.CQuery_ReportListManager.GetCQuery_ReportListById(Convert.ToInt32(ItemID));
        if (mCQuery_ReportList != null)
        {
            if (!LoginLogic.RobotLogin())
            {
                if (!MasterHelper.IsAdmin)
                {//不是管理员就检查权限
                    if (mCQuery_ReportList.LuruId != MasterHelper.Luruid)
                    {//如果不是作者本人就检查权限
                        ReportLogic.CheckUserRight(mCQuery_ReportList.Guid);
                    }
                }
            }
            txbShortView.Text = mCQuery_ReportList.ShortView;
        }
        else
        {
            Response.Write("参数错误");
            Response.End();
        }
        SqlFrom = mCQuery_ReportList.SqlString;//赋值给sqlForm
        OrderColum = mCQuery_ReportList.OrderColum;//赋值给排序用字段
        Replacemode = mCQuery_ReportList.ReplaceMode == "1";

        InitGrid(mCQuery_ReportList);//动态创建表头
        SetAdoHelper(mCQuery_ReportList);//获取ADOHelper
        GerenQueryControls(mCQuery_ReportList);//创建查询条件

        if (mCQuery_ReportList.FormID != "Empty")
        {//有反馈表单关联
            if (!IsPostBack)
            {
                btnReturn.OnClientClick = Grid1.GetNoSelectionAlertReference("至少选择一项！")
                    + Window1.GetShowReference("CQuery_ShowForm.aspx?id=" + mCQuery_ReportList.FormID, "填写反馈表单");

            }
        }
        else
        {//无反馈表单
            btnReturn.Enabled = false;
        }

        if (mCQuery_ReportList.LinkReportID != "Empty")
        {//有的话再赋值
            LinkReportID = mCQuery_ReportList.LinkReportID;
        }
        else
        {//无关联表单就不要显示关联表单按钮
            btnRefer.Enabled = false;
        }

        if (RequestHelper.GetCookie(PageID).Length > 0)
        {//说明是关联表单，需要直接显示数据
            SetSqlWhere();
            BindGrid();
        }
    }

    #region 生成动态控件

    /// <summary>
    /// 生成动态控件
    /// </summary>
    /// <param name="mCQuery_ReportList"></param>
    private void GerenQueryControls(CQuery_ReportList mCQuery_ReportList)
    {
        bool ControlEnable = true;//指示控件是否开启，如果是关联表单，那么关闭。因为不需要开启，直接查询显示
        if (RequestHelper.GetCookie(PageID).Length > 0)
        {
            ControlEnable = false;
        }
        Cquery_ColumList ccl = new Cquery_ColumList();
        OQLCompare cmp = new OQLCompare(ccl);
        OQLCompare cmpresult = (
            cmp.Comparer(ccl.Guid, OQLCompare.CompareType.Equal, mCQuery_ReportList.Guid)
            & cmp.Comparer(ccl.Isinuse, OQLCompare.CompareType.Equal, 1)
            & cmp.Comparer(ccl.IsQuery, OQLCompare.CompareType.Equal, 1)
        );//guid isinuse 过滤条件
        OQL q = new OQL(ccl);
        q.Select().Where(cmpresult).OrderBy(ccl.Paixu, "asc");

        Modlist = EntityQuery<Cquery_ColumList>.QueryList(q, ccl);//放到公用的组合列表里
        RowsAllCount = Modlist.Count;//所有行的查询条件数总和
        int ColumNumber = 2;//每行的控件数
        RowsCount = (RowsAllCount % ColumNumber == 0) ? RowsAllCount / ColumNumber : RowsAllCount / ColumNumber + 1;//计算FormRow的行数
        for (int i = 0; i < RowsCount; i++)
        {
            FormRow row = new FormRow();
            row.ID = "rowUser" + i;
            for (int j = 0; j < ColumNumber; j++)
            {
                int x = i * ColumNumber + j;
                if (x >= RowsAllCount)
                {
                    continue;
                }
                Cquery_ColumList cclx = (Cquery_ColumList)Modlist[x];
                //LogHelper.Debug(i.ToString() + "*" + j.ToString() + "-1=" + x.ToString());

                switch (cclx.QueryType)
                {
                    case "文本":
                        FineUI.TextBox tbx = new FineUI.TextBox();
                        tbx.ID = cclx.ColumID;
                        tbx.Label = cclx.ColumName.Length == 0 ? cclx.ColumID : cclx.ColumName;
                        tbx.Text = cclx.DefaultValue;
                        tbx.Enabled = ControlEnable;
                        if (Replacemode)
                        {
                            tbx.Required = true;
                        }
                        if (OrderColum == cclx.ColumID)
                        {
                            tbx.Text = RequestHelper.GetCookie(PageID);
                        }
                        row.Items.Add(tbx);
                        break;
                    case "数字":
                        FineUI.NumberBox nbx = new NumberBox();
                        nbx.ID = cclx.ColumID + "start";
                        nbx.Text = cclx.DefaultValue;
                        nbx.Label = cclx.ColumName.Length == 0 ? cclx.ColumID + " 起" : cclx.ColumName + " 起";
                        if (Replacemode)
                        {
                            nbx.Required = true;
                        }
                        nbx.Enabled = ControlEnable;
                        if (OrderColum == cclx.ColumID)
                        {
                            nbx.Text = RequestHelper.GetCookie(PageID);
                        }
                        row.Items.Add(nbx);
                        FineUI.NumberBox nbxx = new NumberBox();
                        nbxx.ID = cclx.ColumID + "end";
                        nbxx.Text = cclx.DefaultValue;
                        nbxx.Label = cclx.ColumName.Length == 0 ? cclx.ColumID + " 止" : cclx.ColumName + " 止";
                        if (Replacemode)
                        {
                            nbxx.Required = true;
                        }
                        nbxx.Enabled = ControlEnable;
                        if (OrderColum == cclx.ColumID)
                        {
                            nbxx.Text = RequestHelper.GetCookie(PageID);
                        }
                        row.Items.Add(nbxx);
                        break;
                    case "日期":
                        DateTime dt = DateTime.Now;
                        if (cclx.DefaultValue.Trim().Length > 0)
                        {
                            DateTime.TryParse(cclx.DefaultValue, out dt);
                        }
                        FineUI.DatePicker dp = new DatePicker();
                        dp.ID = cclx.ColumID + "start";
                        if (ControlEnable)
                        {//控件为可编辑状态时才能显示默认时间，不可编辑时，不显示，不替换
                            if (cclx.DefaultValue.Trim().Length > 0)
                            {//有默认值再赋值
                                dp.SelectedDate = dt;
                            }
                        }
                        dp.Label = cclx.ColumName.Length == 0 ? cclx.ColumID + " 起" : cclx.ColumName + " 起";
                        if (Replacemode)
                        {
                            dp.Required = true;
                        }
                        dp.Enabled = ControlEnable;
                        if (OrderColum == cclx.ColumID)
                        {
                            DateTime.TryParse(RequestHelper.GetCookie(PageID), out dt);
                            dp.SelectedDate = dt;
                        }
                        row.Items.Add(dp);
                        FineUI.DatePicker dpx = new DatePicker();
                        dpx.ID = cclx.ColumID + "end";
                        if (ControlEnable)
                        {
                            if (cclx.DefaultValue.Trim().Length > 0)
                            {//有默认值再赋值
                                dpx.SelectedDate = dt;
                            }
                        }

                        dpx.Label = cclx.ColumName.Length == 0 ? cclx.ColumID + " 止" : cclx.ColumName + " 止";
                        if (Replacemode)
                        {
                            dpx.Required = true;
                        }
                        dpx.Enabled = ControlEnable;
                        if (OrderColum == cclx.ColumID)
                        {
                            DateTime.TryParse(RequestHelper.GetCookie(PageID), out dt);
                            dpx.SelectedDate = dt;
                        }
                        row.Items.Add(dpx);
                        break;
                    case "下拉框":
                        FineUI.DropDownList ddl = new FineUI.DropDownList();
                        if (!Replacemode)
                        {//替换模式不需要，因为所有的值都必须替换
                            ddl.Items.Add("不选择", "NoSelect");
                        }

                        foreach (string keys in cclx.DefaultValue.Split(','))
                        {
                            if (keys.Contains("^"))
                            {
                                ddl.Items.Add(keys.Split('^')[0], keys.Split('^')[1]);
                            }
                            else
                            {
                                ddl.Items.Add(keys, keys);
                            }
                        }
                        ddl.Items.Add("为空", "IsNull");
                        ddl.ID = cclx.ColumID;
                        if (cclx.DefaultValue.Trim().Length > 0)
                        {
                            ddl.SelectedValue = cclx.DefaultValue;
                        }
                        ddl.Label = cclx.ColumName.Length == 0 ? cclx.ColumID : cclx.ColumName;
                        if (Replacemode)
                        {
                            ddl.Required = true;
                        }
                        ddl.Enabled = ControlEnable;
                        if (OrderColum == cclx.ColumID)
                        {

                            ddl.SelectedValue = RequestHelper.GetCookie(PageID);
                        }
                        row.Items.Add(ddl);
                        break;
                    default:
                        break;
                }
            }
            Form2.Rows.Add(row);
        }
    }

    #endregion


    #region 根据生成的控件来形成SQL语句

    /// <summary>
    /// 根据生成的控件来形成SQL语句
    /// </summary>
    private void SetSqlWhere()
    {
        string sqlReplace = SqlFrom;

        SqlWhere = " 1=1";
        int ColumNumber = 2;//每行的控件数
        for (int i = 0; i < RowsCount; i++)
        {
            FormRow rowUser = Form2.FindControl("rowUser" + i) as FormRow;
            for (int j = 0; j < ColumNumber; j++)
            {
                int x = i * ColumNumber + j;
                if (x >= RowsAllCount)
                {
                    continue;
                }
                Cquery_ColumList cclx = (Cquery_ColumList)Modlist[x];
                //  LogHelper.Debug(i.ToString() + "*" + j.ToString() + "-1=" + x.ToString());

                switch (cclx.QueryType)
                {
                    case "文本":
                        FineUI.TextBox tbx = (FineUI.TextBox)rowUser.FindControl(cclx.ColumID);
                        if (tbx.Text.Trim().Length > 0)
                        {
                            SqlWhere += " and " + cclx.ColumID + " like '%" + tbx.Text.Trim() + "%'";
                        }
                        //替换SQL语句中的字段
                        string text = cclx.ColumID + "='" + tbx.Text.Trim() + "'";
                        ReportLogic.getReplaceModeSql(text, cclx.ColumID, ref SqlFrom);
                        break;
                    case "数字":
                        FineUI.NumberBox nbx = (FineUI.NumberBox)rowUser.FindControl(cclx.ColumID + "start");
                        FineUI.NumberBox nbxx = (FineUI.NumberBox)rowUser.FindControl(cclx.ColumID + "end");
                        if (nbx.Text.Trim().Length > 0 && nbxx.Text.Trim().Length > 0)
                        {//起始都填了
                            SqlWhere += " and ( " + cclx.ColumID + " >= " + nbx.Text.Trim();
                            SqlWhere += " and " + cclx.ColumID + " <= " + nbxx.Text.Trim() + " ) ";
                            ReportLogic.getReplaceModeSql(cclx.ColumID + " >= " + nbx.Text.Trim() + " and " + cclx.ColumID + " <= " + nbxx.Text.Trim()
                                , cclx.ColumID, ref SqlFrom);
                        }
                        else if (nbx.Text.Trim().Length > 0 && nbxx.Text.Trim().Length == 0)
                        {//只填了起
                            SqlWhere += " and  " + cclx.ColumID + " >= " + nbx.Text.Trim();
                            ReportLogic.getReplaceModeSql(cclx.ColumID + " >= " + nbx.Text.Trim(), cclx.ColumID, ref SqlFrom);
                        }
                        else if (nbxx.Text.Trim().Length > 0 && nbx.Text.Trim().Length == 0)
                        {//只填了止
                            SqlWhere += " and " + cclx.ColumID + " <= " + nbxx.Text.Trim();
                            ReportLogic.getReplaceModeSql(cclx.ColumID + " <= " + nbxx.Text.Trim(), cclx.ColumID, ref SqlFrom);
                        }
                        break;
                    case "日期":

                        FineUI.DatePicker dp = (FineUI.DatePicker)rowUser.FindControl(cclx.ColumID + "start");
                        FineUI.DatePicker dpx = (FineUI.DatePicker)rowUser.FindControl(cclx.ColumID + "end");
                        if (dp.Text.Length > 0 && dpx.Text.Length > 0)
                        {//起始都有
                            if (dbtype == DBMSType.Oracle)
                            {
                                SqlWhere += " and   " + cclx.ColumID + " >=  to_Date('" + dp.Text + " 00:00:00','yyyy-MM-dd HH24:mi:ss') ";
                                SqlWhere += " and   " + cclx.ColumID + " <=  to_Date('" + dpx.Text + " 23:59:59','yyyy-MM-dd HH24:mi:ss')";
                                //替换SQL语句中的字段
                                ReportLogic.getReplaceModeSql(cclx.ColumID + " >=  to_Date('" + dp.Text + " 00:00:00','yyyy-MM-dd HH24:mi:ss') and " + cclx.ColumID + " <=  to_Date('" + dpx.Text + " 23:59:59','yyyy-MM-dd HH24:mi:ss')"
                                    , cclx.ColumID, ref SqlFrom);
                            }
                            else
                            {
                                SqlWhere += " and ( " + cclx.ColumID + " >= '" + dp.Text + " 0:00:00'";
                                SqlWhere += " and " + cclx.ColumID + " <= '" + dpx.Text + " 23:59:59' ) ";
                                //替换SQL语句中的字段
                                ReportLogic.getReplaceModeSql(cclx.ColumID + " >= '" + dp.Text + " 0:00:00' and " + cclx.ColumID + " <= '" + dpx.Text + " 23:59:59' ) "
                                    , cclx.ColumID, ref SqlFrom);

                            }
                        }
                        else if (dp.Text.Length > 0 & dpx.Text.Length == 0)
                        {//只有起始时间
                            if (dbtype == DBMSType.Oracle)
                            {
                                SqlWhere += " and   " + cclx.ColumID + " >=  to_Date('" + dp.Text + " 00:00:00','yyyy-MM-dd HH24:mi:ss') ";
                                //替换SQL语句中的字段
                                ReportLogic.getReplaceModeSql(cclx.ColumID + " >=  to_Date('" + dp.Text + " 00:00:00','yyyy-MM-dd HH24:mi:ss') ", cclx.ColumID, ref sqlReplace);
                            }
                            else
                            {
                                SqlWhere += " and  " + cclx.ColumID + " >= '" + dp.Text + " 00:00:00'";
                                //替换SQL语句中的字段
                                ReportLogic.getReplaceModeSql(cclx.ColumID + " >= '" + dp.Text + " 00:00:00'", cclx.ColumID, ref SqlFrom);
                            }
                        }
                        else if (dpx.Text.Length > 0 & dp.Text.Length == 0)
                        {//只有终止时间
                            if (dbtype == DBMSType.Oracle)
                            {
                                SqlWhere += " and   " + cclx.ColumID + " <=  to_Date('" + dpx.Text + " 23:59:59','yyyy-MM-dd HH24:mi:ss')";
                                //替换SQL语句中的字段
                                ReportLogic.getReplaceModeSql(cclx.ColumID + " <=  to_Date('" + dpx.Text + " 23:59:59','yyyy-MM-dd HH24:mi:ss')", cclx.ColumID, ref sqlReplace);
                            }
                            else
                            {
                                SqlWhere += " and  " + cclx.ColumID + " <= '" + dpx.Text + " 23:59:59'";
                                //替换SQL语句中的字段
                                ReportLogic.getReplaceModeSql(cclx.ColumID + " <= '" + dpx.Text + " 23:59:59'", cclx.ColumID, ref SqlFrom);
                            }
                        }

                        break;
                    case "下拉框":
                        FineUI.DropDownList ddl = (FineUI.DropDownList)rowUser.FindControl(cclx.ColumID);
                        if (ddl.SelectedValue != "NoSelect")
                        {//有选择
                            if (ddl.SelectedValue == "IsNull")
                            {
                                SqlWhere += " and (" + cclx.ColumID + " = '' or " + cclx.ColumID + " is null)";
                                //替换SQL语句中的字段
                                ReportLogic.getReplaceModeSql("(" + cclx.ColumID + " = '' or " + cclx.ColumID + " is null)", cclx.ColumID, ref SqlFrom);
                            }
                            else
                            {
                                SqlWhere += " and " + cclx.ColumID + " = '" + ddl.SelectedValue + "'";
                                //替换SQL语句中的字段
                                ReportLogic.getReplaceModeSql(cclx.ColumID + " = '" + ddl.SelectedValue + "'", cclx.ColumID, ref SqlFrom);
                            }
                        }
                        break;
                    default:
                        break;
                }
            }

        }

        if (RequestHelper.GetCookie(PageID).Length > 0)
        {//说明是关联表单，需要生成关联表单的数据
            // LogHelper.Debug("关联表单，需要生成关联表单的数据");
            SqlWhere += " and " + OrderColum + "='" + RequestHelper.GetCookie(PageID) + "'";
            ReportLogic.getReplaceModeSql(OrderColum + "='" + RequestHelper.GetCookie(PageID) + "'", OrderColum, ref SqlFrom);

        }
    }

    #endregion
    /// <summary>
    /// 设置查询助手
    /// </summary>
    /// <param name="mCQuery_ReportList"></param>
    private void SetAdoHelper(CQuery_ReportList mCQuery_ReportList)
    {
        //初始化数据源模型
        CQuery_ConnString ccs = new CQuery_ConnString();
        ccs.Id = Convert.ToInt64(mCQuery_ReportList.ConnID);
        EntityQuery<CQuery_ConnString> query = new EntityQuery<CQuery_ConnString>(ccs);
        query.FillEntity(ccs);

        //获取数据源类型
        dbtype = DBTypeLogic.getDbmsTypeByString(ccs.DbType);
       

        adohelper = MyDB.GetDBHelper(dbtype, ccs.ConnString);


    }



    #region 绑定数据源，绑定前生成sql
    protected void BindGrid()
    {
        BindGrid(false);
    }

    protected void BindGrid(bool IsToExcel)
    {

        string sqlFull = string.Empty;//存放完整的sql
        string sqlAllCount = string.Empty;//存放查询总数的sql
        string ExCloums = string.Empty;

        if (IsToExcel)
        {//如果是导出Excel,导出的表头要中文注释
            ExCloums = ExcelColums;
        }
        else
        {
            ExCloums = Colums;
        }
        if (!Replacemode)
        {//非替换模式，生成where条件
            //获取列，取一行数据就行
            string sqlFormatSqlserver = "select {0} from ({1}) tt  {2} order by {3} desc";
            string sqlFormat = "select {0} from ({1}) tt  {2} ";
            string sqlAllCountFormatSqlserver = "select count(*) as count from ({0}) tt  {1} order by {2} desc";
            string sqlAllCountFormat = "select count(*) as count from ({0}) tt  {1}";
            if (dbtype == DBMSType.SqlServer)
            {
                sqlFull = string.Format(sqlFormatSqlserver, ExCloums, SqlFrom, "where " + SqlWhere, OrderColum);
                sqlAllCount = string.Format(sqlAllCountFormat, SqlFrom, "where " + SqlWhere, OrderColum);
            }
            else
            {
                sqlFull = string.Format(sqlFormat, ExCloums, SqlFrom, "where " + SqlWhere);
                sqlAllCount = string.Format(sqlAllCountFormat, SqlFrom, "where " + SqlWhere, OrderColum);

            }
        }
        else
        {//替换模式,直接赋值
            sqlFull = SqlFrom;

            SqlWhere = "";
        }
        /////单独处理sqlserver的order by 问题

        /**
         * 时间：2013年1月21日 11:14:27
         * 说明：计算数据集条数的sql也要进行值替换
         * */
        sqlAllCount = ReportLogic.DefaultValueFormat(sqlAllCount);//处理下替换值
        sqlFull = ReportLogic.DefaultValueFormat(sqlFull);//处理下替换值

        if (IsToExcel)
        {//如果是导出Excel
            // LogHelper.Debug("导出生成dataset" + DateTime.Now.ToString());

            FTchina.OfficeHelper.ToExcel.GridView2Excel(adohelper.ExecuteDataSet(sqlFull));
            // FTchina.OfficeHelper.ToExcel.DataSetToExcel(adohelper.ExecuteDataSet(sqlFull));---慢，
            // LogHelper.Debug("导出结束" + DateTime.Now.ToString());

            return;
        }
        int AllCount = 0;
        if (CacheHelper.IsExits(SqlFrom + SqlWhere))
        {
            AllCount = (int)CacheHelper.Get(SqlFrom + SqlWhere);
        }
        else
        {
            if (!Replacemode)
            {
               // 非替换模式
               AllCount = Convert.ToInt32(adohelper.ExecuteScalar(sqlAllCount).ToString());
               // Alert.Show("非替换模式" + AllCount);
            }
            else
            {//替换模式
                AllCount = adohelper.ExecuteDataSet(sqlFull).Tables[0].Rows.Count;
            }
            CacheHelper.Insert(SqlFrom + SqlWhere, AllCount, 60);
        }
        string sqlSingle = PWMIS.Common.SQLPage.MakeSQLStringByPage(dbtype, sqlFull, SqlWhere, PageSize, Grid1.PageIndex + 1, AllCount);
        //Alert.Show(sqlSingle);
        //Alert.Show(dbtype + AllCount + "--****-" + sqlSingle);
        // FTchina.Library.LogHelper.Debug("替换sqlSingle" + sqlSingle);

        DataTable dt = adohelper.ExecuteDataSet(sqlSingle).Tables[0];
        Grid1.RecordCount = AllCount;
        Grid1.DataSource = dt;
        Grid1.DataBind();
        Grid1.SelectedRowIndex = 0;
        //LogHelper.Debug(dt.Rows.Count + "绑定执行了" + AllCount + sqlSingle);
    }

    #endregion
    /// <summary>
    ///动态创建表头
    /// </summary>
    /// <param name="Modlist"></param>
    private void InitGrid(CQuery_ReportList mCQuery_ReportList)
    {
        Cquery_ColumList ccl = new Cquery_ColumList();
        OQLCompare cmp = new OQLCompare(ccl);
        OQLCompare cmpresult = (cmp.Comparer(ccl.Guid, OQLCompare.CompareType.Equal, mCQuery_ReportList.Guid)
            & cmp.Comparer(ccl.Isinuse, OQLCompare.CompareType.Equal, "1")
            & cmp.Comparer(ccl.IsShow, OQLCompare.CompareType.Equal, "1")
        );//guid isinuse 过滤条件
        OQL q = new OQL(ccl);
        q.Select().Where(cmpresult).OrderBy(ccl.Paixu, "ASC");
        List<Cquery_ColumList> Modlist = EntityQuery<Cquery_ColumList>.QueryList(q, ccl);
        int w = 1;//用于动态计算表格宽度，小于750，就填充为750，大于8个格，就计算为8*100
        foreach (Cquery_ColumList cclx in Modlist)
        {
            FineUI.BoundField bf;
            bf = new FineUI.BoundField();
            bf.DataField = cclx.ColumID;
            bf.DataFormatString = "{0}";
            bf.HeaderText = cclx.ColumName.Length > 0 ? cclx.ColumName : cclx.ColumID;
            Grid1.Columns.Add(bf);
            Colums += cclx.ColumID + ",";
            ExcelColums += cclx.ColumID + ((cclx.ColumName.Length > 0) ? " as " + cclx.ColumName : "") + ",";
            w++;
        }

        Grid1.Width = w < 6 ? Unit.Pixel(700) : Unit.Pixel(w * 150);//表格宽度。

        Colums = Colums.TrimEnd(',');//去除最后一个，赋值给Colums，查询字段用
        ExcelColums = ExcelColums.TrimEnd(',');//去除最后一个，赋值给Colums，查询字段用
        Grid1.DataKeyNames = new string[] { OrderColum };
    }



    /// <summary>
    /// 分页事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Grid1_PageIndexChange(object sender, FineUI.GridPageEventArgs e)
    {
        Grid1.PageIndex = e.NewPageIndex;
        SetSqlWhere();//先获取SQL条件
        BindGrid();
    }









    #region 导出Excel
    /// <summary>
    /// 带过滤条件的导出，不分页
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnExcel_click(object sender, EventArgs e)
    {
        //LogHelper.Debug("btnExcel_click" + DateTime.Now.ToString());
        SetSqlWhere();//先获取SQL条件
        BindGrid(true);

    }


    #endregion
    /// <summary>
    /// 反馈
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnReturn_click(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        int[] selections = Grid1.SelectedRowIndexArray;
        foreach (int rowIndex in selections)
        {
            sb.Append(Grid1.DataKeys[rowIndex][0].ToString() + ",");
        }

        //把唯一关键值列放到Cookie中，反馈的时候直接打开取用
        RequestHelper.WriteCookie("OrderColumValue", sb.ToString().TrimEnd(','));
        RequestHelper.WriteCookie("OrderColumName", OrderColum);

    }
    /// <summary>
    /// 查询按钮
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnQuery_click(object sender, EventArgs e)
    {
        SetSqlWhere();
        BindGrid();
    }
    /// <summary>
    /// 查看关联表单
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnRefer_click(object sender, EventArgs e)
    {
        if (Grid1.SelectedRowIndexArray.Length != 1)
        {
            Alert.Show("只能选择一项进行查看");
            return;
        }
        StringBuilder sb = new StringBuilder();
        int[] selections = Grid1.SelectedRowIndexArray;
        foreach (int rowIndex in selections)
        {
            sb.Append(Grid1.DataKeys[rowIndex][0].ToString() + ",");
        }

        //把唯一关键值列放到Cookie中，查看关联表单时取用
        string pageid = this.GetHashCode().ToString();
        RequestHelper.WriteCookie(pageid, sb.ToString().TrimEnd(','));
        //LogHelper.Debug("xierucookie" + sb.ToString().TrimEnd(',') + "ddd" + RequestHelper.GetCookie(pageid));
        // LogHelper.Debug("btnRefer_click" + sb.ToString().TrimEnd(','));

        string s = Window1.GetShowReference("CQuery_ShowReport.aspx?PageID=" + pageid + "&id=" + LinkReportID, "查看关联表单");
        PageContext.RegisterStartupScript(s);
    }
    /// <summary>
    /// 弹出窗口返回的处理
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Window1_Close(object sender, EventArgs e)
    {

        SetSqlWhere();
        BindGrid();
    }

}






